/* ZoomView.cpp
Copyright (c) 2008 Michael Zahniser
Please note the license terms (MIT license) at the end of this document.

Function definitions for the ZoomView class.
*/

#include "ZoomView.h"

#include "Interface.h"
#include "PixMap.h"
#include "_common/min_max.h"



ZoomView::ZoomView(Surface image)
	: image(image), zoom(-1), offsetX(0), offsetY(0)
{
	lock = SDL_CreateMutex();
}



ZoomView::~ZoomView()
{
	SDL_DestroyMutex(lock);
}



void ZoomView::SetImage(Surface image)
{
	SDL_mutexP(lock);
	this->image = image;
	SDL_mutexV(lock);
}



// Get the bounds of the image within this view.
Rectangle ZoomView::ImagePosition() const
{
	Rectangle rect;
	
	SDL_mutexP(lock);
	if(image)
		rect.Set(offsetX, offsetY, image.Width() * zoom, image.Height() * zoom);
	SDL_mutexV(lock);
	
	return rect;
}



// Get the zoom factor.
int ZoomView::Zoom() const
{
	return zoom;
}



// Center the image, and optionally zoom it to the given amount.
void ZoomView::Recenter(int zoom)
{
	this->zoom = -zoom;
}



// Handle an event. If the event involves (x, y) coordinates, they have been
// translated such that (0, 0) is the top left corner of this View.
// This function should return false if this view does not support the given
// event and wants other views to have a chance to handle it.
bool ZoomView::Handle(const SDL_Event &event)
{
	static int motionX = 0;
	static int motionY = 0;
	static bool isDragging = false;

	if(event.type == SDL_MOUSEBUTTONDOWN)
	{
		motionX = 0;
		motionY = 0;
		isDragging = false;
	}
	else if(event.type == SDL_MOUSEMOTION)
	{
		if(event.motion.state & SDL_BUTTON(1))
		{
			offsetX += event.motion.xrel;
			offsetY += event.motion.yrel;
		}

		motionX += event.motion.xrel;
		motionY += event.motion.yrel;
		isDragging |= (motionX * motionX + motionY * motionY > 25);
	}
	else if(event.type == SDL_MOUSEBUTTONUP)
	{
		if(!isDragging)
		{
			int oldZoom = zoom;

			if(event.button.button == SDL_BUTTON_LEFT && zoom < 16)
				zoom *= 2;
			else if(event.button.button == SDL_BUTTON_RIGHT && zoom > 1)
				zoom /= 2;

			// We want:
			// (click - offset) / oldZoom = (click - newOffset) / zoom.
			// (click - offset) * zoom = (click - newOffset) * oldZoom.
			// click * zoom - offset * zoom = click * oldZoom - newOffset * oldZoom.
			// (click * (oldZoom - zoom) + offset * zoom) / oldZoom = newOffset.
			offsetX = (static_cast<Sint16>(event.button.x) * (oldZoom - zoom) + offsetX * zoom) / oldZoom;
			offsetY = (static_cast<Sint16>(event.button.y) * (oldZoom - zoom) + offsetY * zoom) / oldZoom;
		}
	}
	else
		return false;

	return true;
}



// Draw the view in the given surface. The surface is passed as a (shallow)
// copy so that it is impossible for derived classes to modify View::surface
// to point to anything other than what Interface assigns to it.
void ZoomView::Draw(Surface surface) const
{
	SDL_mutexP(lock);
	
	if(!image)
	{
		surface.Erase(surface.Color(255));
		SDL_mutexV(lock);
		return;
	}
	
	// The first time that we have an actual image after a recenter is
	// requested, figure out the offsets necessary to center it.
	if(zoom < 0)
	{
		zoom = -zoom;
		offsetX = (surface.Width() - zoom * image.Width()) / 2;
		offsetY = (surface.Height() - zoom * image.Height()) / 2;
	}
	
	Surface &to = surface;
	const Surface &from = image;

	// Figure out the dimensions of the region we'll be drawing into.
	int width = maximum(0, minimum(to.Width(), from.Width() * zoom + offsetX));
	int rightMargin = to.Width() - width;
	int height = maximum(0, minimum(to.Height(), from.Height() * zoom + offsetY));
	int bottomMargin = to.Height() - height;

	// The left margin cannot be less than 0 or more than to.w.
	int leftMargin = maximum(0, minimum(to.Width(), offsetX));
	width -= leftMargin;
	// Similarly with the top margin.
	int topMargin = maximum(0, minimum(to.Height(), offsetY));
	height -= topMargin;

	// Fill in the margins with white.
	Uint32 white = to.Color(255);
	to.FillRect(0, 0, to.Width(), topMargin, white);
	to.FillRect(0, to.Height() - bottomMargin, to.Width(), bottomMargin, white);
	to.FillRect(0, topMargin, leftMargin, height, white);
	to.FillRect(to.Width() - rightMargin, topMargin, rightMargin, height, white);

	// The first enlarged pixel should contain this number of screen pixels.
	int blockX = (offsetX >= 0) ? zoom : offsetX % zoom + zoom;
	int blockY = (offsetY >= 0) ? zoom : offsetY % zoom + zoom;

	// Get a sub-surface containing only the pixels of the source image
	// that we will be using. Round the size of the region up, to include
	// possible fractional pixels visible on all sides.
	Surface fromRegion = from.Region(
		maximum(0, -offsetX / zoom), maximum(0, -offsetY / zoom),
		(width - blockX + zoom - 1) / zoom + 1, (height - blockX + zoom - 1) / zoom + 1);

	// If the zoom factor is 1, we can just use SDL_BlitSurface.
	if(zoom == 1)
	{
		fromRegion.Blit(to, leftMargin, topMargin);
		SDL_mutexV(lock);
		return;
	}

	// Access the pixels of the "from" and "to" surfaces, locking if necessary.
	ConstPixMap fromPixels(fromRegion);
	PixMap toPixels(to);

	// Get an iterator to the starting pixel in the source image.
	const Uint32 *fromBegin = fromPixels.Begin(0);
	int fromPitch = fromPixels.Pitch();

	// Get the starting pixel in the destination.
	// We always fill the whole surface, so start with the first pixel.
	Uint32 *toBegin = toPixels.Begin(topMargin) + leftMargin;
	int toPitch = toPixels.Pitch();

	while(height > 0)
	{
		// Get a pointer to the start of this row of the source image.
		const Uint32 *it = fromBegin;
		fromBegin += fromPitch;

		// Get an iterator for copying the pixel data to the screen.
		Uint32 *out = toBegin;

		// Draw the visible portion of the image for this row.
		const Uint32 *end = out + width;
		for(Uint32 *blockEnd = out + blockX; out != end; ++out)
		{
			if(out == blockEnd)
			{
				// Advance to the next source pixel.
				blockEnd += zoom;
				++it;
			}
			*out = *it;
		}

		// Copy this row (blockY - 1) times.
		const Uint32 *copySource = toBegin;
		Uint32 *toCopyEnd = toBegin + toPitch * minimum(blockY, height);
		height -= blockY;
		blockY = zoom;
		for(toBegin += toPitch; toBegin < toCopyEnd; toBegin += toPitch)
			memcpy(toBegin, copySource, width * sizeof(Uint32));
	}

	SDL_mutexV(lock);
}



/* Copyright (c) 2008 Michael Zahniser

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE. */
